<?php
/**
 * Create by PhpStorm.
 * User : ZhangDali
 * Date : 2023/2/13
 * Time : 18:12
 */

if ($_POST) {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379, 5);
    $redis->auth('redis密码');

    $visit = $redis->get(get_client_ip());
    if (empty($visit)) {
        $visit = 0;
        $redis->set(get_client_ip(), $visit);
        $times = strtotime(date('Y-m-d 23:59:59')) - time();
        $redis->expire(get_client_ip(), $times);
    }
    if(json_decode($_POST['data'],true)['prompt'] == '我朋友叫大力'){//输入暗号清空体验次数
        $redis->del(get_client_ip());
        echoJson('', 201, '体验次数已重置！');
    }
    if ($visit >= 10) {
        echoJson('', 201, '今天体验够啦，明天再来吧！');
    }
    $str = "**************下面是最新访问" . date("Y-m-d H:i:s") . "*****************" . "\n\r";
    $appkey = "sk-wp9dMYFHdHJ6K3OH8W5pT3BlbkFJ***********你的秘钥*********";
    $data = $_POST['data'] ?? '';
    if (empty($data)) {
        echoJson('', 201, '请输入信息！');
    }
    file_put_contents("a.txt", $str . get_client_ip()."问了：".json_decode($data,true)['prompt'] . "\n\r", FILE_APPEND);//记录访问者的问题
    $url = "https://api.openai.com/v1/completions";
    $result = http($url, $data, $appkey);
    if (isset($result['choices'])) {
        file_put_contents("a.txt", $str . "回答：".get_client_ip().':'.$result['choices'][0]['text'] . "\n\r", FILE_APPEND);//记录答案
        $redis->incr(get_client_ip());
        echoJson($result['choices'][0]['text'], 200, '这就是我的回答！');
    }
    echoJson('', 201, 'chatgpt累了，过一会再试试吧！');
}
echoJson('', 201, '看你就不是正规请求！');

function echoJson($data, $status, $msg = "")
{
    echo json_encode(['data' => $data, 'msg' => $msg, 'status' => $status]);
    exit();
}

function http($url, $data, $appkey, $json = true)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    if (!empty($data)) {
        if ($json && is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        if ($json) {
            // 发送JSON数据
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_HTTPHEADER,
                array(
                    'Authorization:Bearer ' . $appkey,
                    'Content-Type: application/json'
                )
            );
        }
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl);
    $errorno = curl_errno($curl);
    if ($errorno) {
        return array('errorno' => false, 'errmsg' => $errorno);
    }
    curl_close($curl);

    return json_decode($res, true);
}

function get_client_ip()
{
    static $ip = null;
    if ($ip !== null) {
        return $ip;
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($arr[0]);
    } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
